package com.example.question.tree.tree2;

import com.example.question.tree.tree1.TreeNode;

public class Code05_112 {
    public static void main(String[] args) {

    }

    private boolean flag = false;

    public boolean hasPathSum1(TreeNode root, int targetSum) {
        preOrder(root, 0, targetSum);
        return flag;
    }

    public void preOrder(TreeNode node, int sum, int targetSum) {
        if (node == null) {
            return;
        }
        // 当前是叶子节点 且值是符合的  找到就结束
        if (node.left == null && node.right == null && node.val + sum == targetSum) {
            flag = true;
            return;
        }
        preOrder(node.left, sum + node.val, targetSum);
        preOrder(node.right, sum + node.val, targetSum);
    }



    public boolean hasPathSum(TreeNode root, int targetSum) {
        return postOrder(root, 0, targetSum);
    }

    public boolean postOrder(TreeNode node, int sum, int targetSum) {
        if (node == null) {
            return false;
        }
        boolean left = postOrder(node.left, sum + node.val, targetSum);
        boolean right = postOrder(node.right, sum + node.val, targetSum);
        if (node.left == null && node.right == null && node.val + sum == targetSum) {
            return true;
        }
        return left || right;
    }


}
